package com.bsoft.gol.hcs.specialist.dao;

import ctd.persistence.annotation.DAOMethod;
import ctd.persistence.annotation.DAOParam;
import ctd.persistence.support.hibernate.HibernateSupportDelegateDAO;
import ctd.persistence.support.hibernate.template.AbstractHibernateStatelessResultAction;
import ctd.persistence.support.hibernate.template.HibernateSessionTemplate;
import ctd.persistence.support.hibernate.template.HibernateStatelessResultAction;
import ctd.util.converter.ConversionUtils;
import com.bsoft.gol.hcs.enumcase.FollowTypeEnum;
import org.hibernate.Query;
import org.hibernate.StatelessSession;
import org.hibernate.criterion.CriteriaSpecification;
import com.bsoft.gol.hcs.specialist.bean.request.GroupChronicRecordQo;
import com.bsoft.gol.hcs.specialist.bean.response.FactorData;
import com.bsoft.gol.hcs.specialist.bean.response.GroupExtendPropertyListResponse;
import com.bsoft.gol.hcs.specialist.bean.response.GroupExtendPropertyResponse;
import hcn.specialist.FusGroupChronicRecordExtendProperty;
import com.bsoft.gol.hcs.utils.CommonUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 入组记录扩展属性dao
 *
 * @author lanyu
 * @date 2021年09月29日 16:04
 */
public abstract class GroupRecordExtendPropertyDAO extends HibernateSupportDelegateDAO<FusGroupChronicRecordExtendProperty> {

    /**
     * 根据病种id和扩展属性id获取入组记录扩展信息
     *
     * @param diseaseTypeId
     * @return
     */
    @DAOMethod(sql = " from FusGroupChronicRecordExtendProperty where diseaseTypeId =:diseaseTypeId and extendId =:extendId order by createTime")
    public abstract List<FusGroupChronicRecordExtendProperty> queryGroupRecordExtendPropertyByDiseaseTypeId(@DAOParam("diseaseTypeId") Long diseaseTypeId, @DAOParam("extendId") Long extendId);
    /**
     * 扩展属性id获取入组记录扩展信息
     *
     * @param extendIdList
     * @return
     */
    @DAOMethod(sql = " select count(1) from FusGroupChronicRecordExtendProperty where diseaseTypeId =:diseaseTypeId and extendId in (:extendIdList) order by createTime")
    public abstract Long getCountGroupRecordExtendPropertyByExtendId(@DAOParam("diseaseTypeId") Long diseaseTypeId, @DAOParam("extendIdList") List<Long> extendIdList);

    /**
     * 根据入组记录id和病种id获取扩展属性信息
     * @param diseaseTypeId
     * @param teamChronicGroupId
     * @return
     */
    @DAOMethod(sql = " from FusGroupChronicRecordExtendProperty where diseaseTypeId =:diseaseTypeId and teamChronicGroupId =:teamChronicGroupId order by createTime")
    public abstract List<FusGroupChronicRecordExtendProperty> findGroupRecordExtendList(@DAOParam("diseaseTypeId") Long diseaseTypeId,@DAOParam("teamChronicGroupId") Long teamChronicGroupId);

    /**
     * 根据入组记录id和病种id获取扩展属性信息
     * @param diseaseTypeId
     * @param teamChronicGroupId
     * @return
     */
    @DAOMethod(sql = " from FusGroupChronicRecordExtendProperty where diseaseTypeId =:diseaseTypeId and teamChronicGroupId =:teamChronicGroupId order by createTime")
    public abstract List<FusGroupChronicRecordExtendProperty> queryGroupRecordExtendList(@DAOParam("diseaseTypeId") Long diseaseTypeId,@DAOParam("teamChronicGroupId") Long teamChronicGroupId);

    /**
     * 删除扩展属性
     * @param groupChronicRecordId
     */
    @DAOMethod(sql =" delete from FusGroupChronicRecordExtendProperty where groupChronicRecordId=:groupChronicRecordId")
    public abstract void deleteExtendPropertyByExtendId(@DAOParam("groupChronicRecordId") Long groupChronicRecordId);

    /**
     * 删除扩展属性
     */
    @DAOMethod(sql =" delete from FusGroupChronicRecordExtendProperty where diseaseTypeId =:diseaseTypeId and teamChronicGroupId =:teamChronicGroupId")
    public abstract void deleteExtendPropertyByDiseaseTypeIdAndTeamChronicGroupId(@DAOParam("diseaseTypeId") Long diseaseTypeId,
                                                                                  @DAOParam("teamChronicGroupId") Long teamChronicGroupId);

    /**
     *
     * 根据病种id获取扩展属性
     * @param qo
     * @return
     */
    public List<GroupExtendPropertyResponse> queryFirstGroupExtendPropertyList(GroupChronicRecordQo qo) {
        HibernateStatelessResultAction<List<GroupExtendPropertyResponse>> action = new AbstractHibernateStatelessResultAction<List<GroupExtendPropertyResponse>>() {
            @Override
            public void execute(StatelessSession ss) throws Exception {
                StringBuilder sqlBuilder = new StringBuilder();
                sqlBuilder.append("SELECT extendId,NAME as name,optGroupFlag,viewDispFlag FROM fus_disease_extend_property where disease_type_id =:diseaseTypeId " +
                        "AND isnull( parentId ) ");
                sqlBuilder.append(" and createTime>=:beginTime and createTime<=:endTime and viewDispFlag = '1' order by createTime ");
                Query query = ss.createSQLQuery(sqlBuilder.toString());
                query.setParameter("diseaseTypeId", qo.getDiseaseTypeId());
                if (CommonUtils.isNotEmpty(qo.getBeginTime())){
                    query.setParameter("beginTime", qo.getBeginTime()+" 00:00:00");
                }
                if (CommonUtils.isNotEmpty(qo.getBeginTime())){
                    query.setParameter("endTime", qo.getEndTime()+" 23:59:59");
                }
                query.setResultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP);
                List<Map> list = query.list();
                List<GroupExtendPropertyResponse> voList = new ArrayList<>();
                if (CommonUtils.isNotEmpty(list)) {
                    for (Map map : list) {
                        voList.add(ConversionUtils.convert(map, GroupExtendPropertyResponse.class));
                    }
                } else {
                    voList = new ArrayList<>();
                }
                setResult(voList);
            }
        };
        HibernateSessionTemplate.instance().execute(action);
        return action.getResult();
    }

    /**
     *
     * 根据病种id获取扩展属性
     * @param qo
     * @return
     */
    public List<GroupExtendPropertyListResponse> querySecondGroupExtendPropertyList(GroupChronicRecordQo qo, String extendId) {
        HibernateStatelessResultAction<List<GroupExtendPropertyListResponse>> action = new AbstractHibernateStatelessResultAction<List<GroupExtendPropertyListResponse>>() {
            @Override
            public void execute(StatelessSession ss) throws Exception {
                StringBuilder sqlBuilder = new StringBuilder();
                sqlBuilder.append("SELECT f.group_chronic_record_id AS groupChronicRecordId,fd.extendId,fd.NAME as name,f.parent_id AS parentId,f.extend_time as extendTime,f.create_time AS createTime,f.create_user_id as createUserId " +
                        "FROM fus_disease_extend_property fd INNER JOIN fus_group_chronic_record_extend_property f ON fd.extendId = f.extend_id " +
                        "AND f.parent_id =:extendId AND f.disease_type_id =:diseaseTypeId ");
                sqlBuilder.append(" and f.create_time >=:beginTime and f.create_time <=:endTime order by f.create_time ");
                Query query = ss.createSQLQuery(sqlBuilder.toString());
                query.setParameter("diseaseTypeId", qo.getDiseaseTypeId());
                query.setParameter("extendId",extendId);
                if (CommonUtils.isNotEmpty(qo.getBeginTime())){
                    query.setParameter("beginTime", qo.getBeginTime()+" 00:00:00");
                }
                if (CommonUtils.isNotEmpty(qo.getBeginTime())){
                    query.setParameter("endTime", qo.getEndTime()+" 23:59:59");
                }
                query.setResultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP);
                List<Map> list = query.list();
                List<GroupExtendPropertyListResponse> voList = new ArrayList<>();
                if (CommonUtils.isNotEmpty(list)) {
                    for (Map map : list) {
                        voList.add(ConversionUtils.convert(map, GroupExtendPropertyListResponse.class));
                    }
                } else {
                    voList = new ArrayList<>();
                }
                setResult(voList);
            }
        };
        HibernateSessionTemplate.instance().execute(action);
        return action.getResult();
    }


    /**
     * @description: 根据专病扩展属性编码、开始时间、结束时间、病人id集合查询专病扩展属性集合
     * @param: factorIdList 专病扩展属性编码集合
     * @param: startTime 专病扩展属性编码修改开始时间
     * @param: endTime 专病扩展属性编码修改结束时间
     * @param: patientIdList 病人id集合
     * @return: java.util.List<specialist.bean.response.FactorData>
     */
    public List<FactorData> executeFactorForDiseasePeriod(List<String> factorIdList, Date startTime, Date endTime, List<String> patientIdList,Byte isLoopExecute,Long routeDetailId, String followType) {

        HibernateStatelessResultAction<List<FactorData>> action = new AbstractHibernateStatelessResultAction<List<FactorData>>() {
            @Override
            public void execute(StatelessSession ss) throws Exception {
                StringBuilder sqlBuilder = new StringBuilder();
                sqlBuilder.append("select patientId,extendId,name,groupChronicRecordId ,extendTime,dataSource from (");
                sqlBuilder.append("SELECT b.patient_id patientId,a.extend_id extendId, a.name name, a.group_chronic_record_id groupChronicRecordId, a.extend_time extendTime ,'1' dataSource ");
                sqlBuilder.append(" FROM fus_group_chronic_record_extend_property a, fus_team_chronic_group_record b ");
                sqlBuilder.append(" WHERE a.team_chronic_group_id = b.team_chronic_group_id AND b.apply_status = '1' ");
                sqlBuilder.append("  AND a.extend_id in(:extendIdList) ");
                if (null != startTime) {
                    sqlBuilder.append("  and  a.extend_time>:startTime ");
                }
                if (null != endTime) {
                    sqlBuilder.append("  and  a.extend_time<:endTime ");
                }
                if (CommonUtils.isNotEmpty(patientIdList)) {
                    sqlBuilder.append(" and b.patient_id in(:patientIdList)");
                }
                sqlBuilder.append(") AS  m ");
                //循环执行机制 0 不执行 1 执行
                if (FollowTypeEnum.FUS_SPECIALIST.getType().equals(followType) && null != isLoopExecute && isLoopExecute == 1) {
                    sqlBuilder.append(" LEFT JOIN fus_factor_data_record f  ON f.patient_id = m.patientId   AND f.route_detail_id = :routeDetailId AND f.team_chronic_group_id = m.groupChronicRecordId WHERE f.id IS NULL  ");
                }
                Query query = ss.createSQLQuery(sqlBuilder.toString());
                query.setParameterList("extendIdList", factorIdList);
                if (null != startTime) {
                    query.setParameter("startTime", startTime);
                }
                if (null != endTime) {
                    query.setParameter("endTime", endTime);
                }
                if (CommonUtils.isNotEmpty(patientIdList)) {
                    query.setParameterList("patientIdList", patientIdList);
                }
                if (FollowTypeEnum.FUS_SPECIALIST.getType().equals(followType) && null != isLoopExecute && isLoopExecute == 1) {
                    query.setParameter("routeDetailId", routeDetailId);
                }
                query.setResultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP);
                List<Map> list = query.list();
                List<FactorData> voList = new ArrayList<>();
                if (CommonUtils.isNotEmpty(list)) {
                    for (Map map : list) {
                        voList.add(ConversionUtils.convert(map, FactorData.class));
                    }
                } else {
                    voList = new ArrayList<>();
                }
                setResult(voList);
            }
        };
        HibernateSessionTemplate.instance().execute(action);
        return action.getResult();
    }
}
